<template>
  <div>
    <div>
      <h2 style="text-align: center">发布新课程</h2>
    </div>
    <!-- 发布新课程 -->
    <el-steps
      :active="2"
      align-center
      process-status="wait"
      style="margin-bottom: 30px"
    >
      <el-step title="填写课程基本信息"></el-step>
      <el-step title="创建课程大纲"></el-step>
      <el-step title="发布课程"></el-step>
    </el-steps>
    <el-button type="text" style="margin-left: 20px" @click="openChapterDialog">
      添加章节
    </el-button>
    <ul class="chapterList">
      <li v-for="chapter in chapterNestedList" :key="chapter.id">
        <p>
          {{ chapter.title }}
          <span class="acts">
            <el-button type="text" @click="openVideoDialog(chapter.id)"
              >添加课时</el-button
            >
            <el-button type="text" @click="editChapter(chapter.id)">
              编辑
            </el-button>
            <el-button type="text" @click="delChapter(chapter.id)"
              >删除</el-button
            >
          </span>
        </p>
        <ul class="chapterList videoList">
          <li v-for="video in chapter.children" :key="video.id">
            <p>
              {{ video.title }}
              <span class="acts">
                <el-button type="text" @click="openEditVideo(video.id)"
                  >编辑</el-button
                >
                <el-button type="text" @click="delVideo(video.id)"
                  >删除</el-button
                >
              </span>
            </p>
          </li>
        </ul>
      </li>
    </ul>
    <!-- 添加章节遮罩层 -->
    <el-dialog
      :title="chapter.id ? '编辑章节' : '添加章节'"
      :visible.sync="dialogChapterVisible"
      width="40%"
    >
      <el-form
        :model="chapter"
        :rules="chapterRules"
        ref="chapterForm"
        label-width="120px"
      >
        <el-form-item label="章节标题" prop="title">
          <el-input v-model="chapter.title" />
        </el-form-item>
        <el-form-item label="章节排序" prop="sort">
          <el-input-number
            v-model="chapter.sort"
            controls-position="right"
            :min="1"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogChapterVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitChapter">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加课时遮罩层 -->
    <el-dialog
      :title="video.id ? '编辑课时' : '添加课时'"
      :visible.sync="dialogVideoVisible"
      width="40%"
    >
      <el-form
        :model="video"
        :rules="videoRules"
        ref="videoForm"
        label-width="120px"
      >
        <el-form-item label="课时标题" prop="title">
          <el-input v-model="video.title" />
        </el-form-item>
        <el-form-item label="课时排序" prop="sort">
          <el-input-number
            v-model="video.sort"
            controls-position="right"
            :min="1"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="是否免费">
          <el-radio v-model="video.isFree" :label="1">免费</el-radio>
          <el-radio v-model="video.isFree" :label="2">收费</el-radio>
        </el-form-item>
        <el-form-item label="上传视频">
          <el-upload
            class="upload-demo"
            :action="`${BASE_URL}/vod/upload`"
            :on-success="handleUpload"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
          >
            <el-button type="primary" size="mini">上传视频</el-button>
            <el-tooltip class="item" effect="dark" placement="right">
              <div slot="content">
                支持3GP、ASF、AVI、DAT、DV、FLV、F4V、GIF、<br />
                M2T、M4V、MJ2、MJPEG、MKV、MOV、MP4、MPE、<br />
                MPG、MPEG、MTS、0GG、QT、RM、RMVB、SwF、<br />
                TS、VOB、wMV、WEBM等视频格式上传
              </div>
              <i class="el-icon-question"></i>
            </el-tooltip>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVideoVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitVideo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 上一步下一步按钮 -->
    <div style="margin-left: 20px">
      <el-button type="primary" plain @click="previous">上一步</el-button>
      <el-button type="primary" @click="next">下一步</el-button>
    </div>
  </div>
</template>

<script>
import chapterApi from "@/api/chapter";
import videoApi from "@/api/video";
import vodApi from "@/api/vod";

export default {
  data() {
    return {
      BASE_URL: process.env.BASE_API, // 获取dev配置文件中的api地址
      fileList: [], // 上传文件的列表
      courseId: "", // 课程id
      chapterNestedList: [], // 课程大纲列表、
      dialogChapterVisible: false, // 课程章节对话框
      dialogVideoVisible: false, // 课程小节对话框
      radio: "",
      chapter: {
        courseId: "",
        title: "",
        sort: 0,
      },
      video: {
        courseId: "",
        chapterId: "",
        title: "",
        videoSourceId: "",
        videoOriginalName: "",
        sort: 0,
        isFree: 0,
      },
      //   章节表单验证规则
      chapterRules: {
        title: [
          { required: true, message: "请输入章节标题", trigger: "blur" },
          { max: 50, message: "长度最大为 50 个字符", trigger: "blur" },
        ],
        sort: [
          { type: "number", message: "序号必须是数字", trigger: "blur" },
          { required: true, message: "请输入序号", trigger: "blur" },
        ],
      },
      //   课时表单验证规则
      videoRules: {
        title: [
          { required: true, message: "请输入章节标题", trigger: "blur" },
          { max: 50, message: "长度最大为 50 个字符", trigger: "blur" },
        ],
        sort: [
          { type: "number", message: "序号必须是数字", trigger: "blur" },
          { required: true, message: "请输入序号", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.init();
  },
  methods: {
    // 视频上传成功之后的回调
    handleUpload(response, file, fileList) {
      // console.log(response);
      // console.log(file);
      // console.log(fileList);

      // 获取视频的编号
      this.video.videoSourceId = response.data.videoSourceId;

      // 获取视频的原始名称
      this.video.videoOriginalName = file.name;
    },
    handleRemove(file, fileList) {
      // 调用api接口删除云端的视频
      vodApi.delVod(this.video.videoSourceId).then((res) => {
        this.video.videoSourceId = "";
        this.video.videoOriginalName = "";
        this.fileList = [];
        // 提示信息
        this.$message({
          type: "success",
          message: "删除成功!",
        });
      });
    },
    handleExceed(files, fileList) {
      this.$message.warning(`想要重新上传新的视频，请先删除之前的视频`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 上一步
    previous() {
      this.$router.push({ path: `/course/info/${this.courseId}` });
    },
    // 下一步
    next() {
      this.$router.push({
        name: "CoursePublish",
        params: { id: this.courseId },
      });
    },
    //   初始化课程大纲
    init() {
      if (this.$route.params && this.$route.params.id) {
        // 根据课程d获取当前要更新的课程信息,绑定到页面中
        this.courseId = this.$route.params.id;
        // console.log(courseId);
        this.getTreeList(this.courseId);
      }
    },
    // 获取课程大纲
    getTreeList(courseId) {
      chapterApi.getTreeList(courseId).then((res) => {
        this.chapterNestedList = res.data;
      });
    },
    // 打开添加章节
    openChapterDialog() {
      this.dialogChapterVisible = true;

      this.fileList = [];
      //   初始化章节表单信息
      this.chapter = {
        id: "",
        title: "",
        sort: 0,
      };
    },
    // 打开添加课时
    openVideoDialog(chapterId) {
      this.dialogVideoVisible = true;
      //   为课时的章节id赋值
      //   this.video.chapterId = chapterId;
      //   初始化课时小节对话框中遗留数据
      this.video = {
        id: "",
        courseId: "",
        chapterId: chapterId,
        title: "",
        videoSourceId: "",
        videoOriginalName: "",
        sort: 0,
        isFree: 0,
      };
    },
    // 提交章节对话框表单数据
    submitChapter() {
      this.$refs["chapterForm"].validate((valid) => {
        if (valid) {
          // 验证通过
          // 判断执行的是什么操作
          if (this.chapter.id) {
            // console.log("更新");
            // 调用更新的方法
            this.updateChapter();
          } else {
            // console.log("添加");
            // 调用添加的方法
            this.addChapter();
          }
        } else {
          //   失败
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 提交课时对话框表单数据
    submitVideo() {
      this.$refs["videoForm"].validate((valid) => {
        if (valid) {
          // 验证通过
          // 判断执行的是什么操作
          if (this.video.id) {
            // console.log("更新");
            // 调用更新的方法
            this.updateVideo();
          } else {
            // console.log("添加");
            // 调用添加的方法
            this.addVideo();
          }
        } else {
          //   失败
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 添加章节
    addChapter() {
      //   在添加之前为课程id赋值
      this.chapter.courseId = this.courseId;
      // 调用添加章节api
      chapterApi.addChapter(this.chapter).then((res) => {
        // 提示成功信息，
        this.$message({
          type: "success",
          message: "添加成功!",
        });
        //   关闭添加对话框
        this.dialogChapterVisible = false;
        //   更新列表数据
        this.init();
      });
    },
    // 添加课时
    addVideo() {
      // 在添加之前为章节id赋值
      this.video.courseId = this.courseId;
      // 调用添加章节api
      videoApi.addVideo(this.video).then((res) => {
        // 提示成功信息，
        this.$message({
          type: "success",
          message: "添加成功!",
        });
        //   关闭添加对话框
        this.dialogVideoVisible = false;
        //   更新列表数据
        this.init();
      });
    },
    // 编辑课程章节
    editChapter(chapterId) {
      // 根据章节id获取章节信息
      chapterApi.getChapter(chapterId).then((res) => {
        this.chapter = res.data;
        // 打开章节对话框
        this.dialogChapterVisible = true;
      });
    },
    // 编辑课时小节
    openEditVideo(videoId) {
      this.fileList = [];
      // 根据课时id获取章节信息
      videoApi.getVideo(videoId).then((res) => {
        this.video = res.data;
        if (this.video.videoOriginalName) {
          // 为上传视频列表对象赋值
          this.fileList = [{ name: this.video.videoOriginalName }];
        }
        // 打开章节对话框
        this.dialogVideoVisible = true;
      });
    },
    // 更新课程章节
    updateChapter() {
      // 调用更新课程章节的api
      chapterApi.updateChapter(this.chapter).then((res) => {
        // 更新成功
        this.$message({
          type: "success",
          message: "修改成功!",
        });
        //   关闭添加对话框
        this.dialogChapterVisible = false;

        //   更新列表数据
        this.init();
      });
    },
    // 更新课程章节
    updateVideo() {
      // 调用更新课程章节的api
      videoApi.updateVideo(this.video).then((res) => {
        // 更新成功
        this.$message({
          type: "success",
          message: "修改成功!",
        });
        //   关闭添加对话框
        this.dialogVideoVisible = false;

        // 重置视频上传列表
        this.fileList = [];

        //   更新列表数据
        this.init();
      });
    },
    //根据id删除课程章节
    delChapter(id) {
      this.$confirm("您确定要删除此章节吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(() => {
          // 点击确认在进行调用chapterApi中的删除api
          chapterApi.delChapter(id).then((res) => {
            // 删除成功
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.init();
          });
          // 重新加载删除后的数据
        })
        .catch(() => {});
    },
    //根据id删除课时小节
    delVideo(id) {
      this.$confirm("您确定要删除此章节吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(() => {
          // 点击确认在进行调用chapterApi中的删除api
          videoApi.delVideo(id).then((res) => {
            // 删除成功
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.init();
          });
          // 重新加载删除后的数据
        })
        .catch(() => {});
    },
  },
};
</script>


<style scoped>
.chapterList {
  position: relative;
  list-style: none;
  margin: 0;
  padding: 0;
}

.chapterList li {
  position: relative;
}

.chapterList p {
  float: left;
  font-size: 20px;
  margin: 10px 0;
  padding: 10px;
  height: 70px;
  line-height: 50px;
  width: 100%;
  border: 1px solid #ddd;
}

.chapterList .acts {
  float: right;
  font-size: 14px;
}

.videoList {
  padding-left: 50px;
}

.videoList p {
  float: left;
  font-size: 14px;
  margin: 10px 0;
  padding: 10px;
  height: 50px;
  line-height: 30px;
  width: 100%;
  border: 1px dotted #ddd;
}
</style>
